package com.lujianfei.powersearch.ui

import androidx.databinding.ObservableArrayList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.DatabindingDiffUtils
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivityViewModel: ViewModel() {

    var searchItemModelFromLongClick: SearchItemModel?= null
    val data = ObservableArrayList<SearchItemModel>()

    var onItemClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemClick: ((SearchItemModel) -> Unit) = {
        onItemClickCallback?.invoke(it)
    }
    var onItemLongClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemLongClick: ((SearchItemModel) -> Unit) = {
        onItemLongClickCallback?.invoke(it)
    }

    fun loadData() {
        viewModelScope.launch {
            val resp = withContext(Dispatchers.IO) {
                val otherModels = SugarRecord.find(SearchItemModel::class.java, "parentId=? order by name", "" + Constant.RootId)
                otherModels.sortByDescending { it.sort }
                appendSubCount(otherModels)
                otherModels
            }
            DatabindingDiffUtils.setData(oldList = data, newList = resp)
        }
    }

    private fun appendSubCount(otherModels: List<SearchItemModel>) {
        for (model in otherModels) {
            val sublist = SugarRecord.find(SearchItemModel::class.java, "parentId=?", "" + model.id)
            model.subCount = sublist.size
        }
    }

    fun setTop(model: SearchItemModel) {
        model.sort = System.currentTimeMillis()
        model.save()
        loadData()
    }

    fun setCancelTop(model: SearchItemModel) {
        model.sort = 0
        model.save()
        loadData()
    }

    fun moveTo(moveToModel: SearchItemModel) {
        searchItemModelFromLongClick?.parentId = moveToModel.id
        searchItemModelFromLongClick?.save()
        loadData()
    }
}